package book.dao.book.impl;


import book.dao.book.BookDao;
import book.util.DbHelper;

import book.exception.SystemBookDbException;
import book.pojo.Book;
import book.pojo.DynamicParameter;
import book.pojo.PageBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.*;
import java.util.Arrays;
import java.util.List;

public class BookDaoImpl implements BookDao {


    @Override
    public int addBook(Book book) {
        try{
            int row = 0;
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
            String sql = "insert into books(title,author,available) values(?,?,?)";
            Object []args = {book.getTitle(),book.getAuthor(),book.isAvailable()};
            row = runner.update(sql,args);
            return row;
        }catch (SQLException e) {
            throw new SystemBookDbException("添加用户表错误："+e.getMessage());
        }
    }

    @Override
    public int deleteBook(Book book) {
        QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
        String sql = "delete from books where id = ?";
        try {
            int row = runner.update(sql,book.getId());
            return row;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateBook(Book book) {
        try{
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
            //2、编写sql
            String sql = "UPDATE books SET title = ?, author = ?, cover = ? ,available = ? WHERE id = ?";
            Object []arg = {book.getTitle(), book.getAuthor(), book.getCover(),book.isAvailable(),book.getId()};
            int row = runner.update(sql,arg);
            return row;
        }catch (SQLException e) {
            throw new SystemBookDbException("添加用户表错误："+e.getMessage());
        }
    }

    @Override
    public Book findBookById(int id) {
        try {
            Book book = null;
            //1、创建Query对象，将数据源对象为参数，runner内部使用完连接会自动返回连接池
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
            //2、编写sql
            String sql = "select * from books where id=?";
            //3、执行查询
            book = runner.query(sql,new BeanHandler<Book>(Book.class),id);
            System.out.println(book);
            return book;
        } catch (SQLException e) {
            throw new SystemBookDbException("根据id用户错误："+e.getMessage());
        }
    }

    @Override
    public List<Book> findAllBooks() {
        try{
            System.out.println("findAllBooks() 方法被调用");
            int row = 0;
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
            String sql = "select * from books";
            List<Book>books = runner.query(sql,new BeanListHandler<Book>(Book.class));
            return books;
        }catch (SQLException e) {
            throw new SystemBookDbException("查询所有用户错误："+e.getMessage());
        }
    }

    @Override
    public PageBean<Book> findAllBooks(PageBean<Book> pageBean) {
        List<Book> list;
        try {
            //1、创建Query对象，将数据源对象为参数，runner内部使用完连接会自动返回连接池
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());

            //*********修改的代码，用于支持动态查询参数*********//

            //2、编写sql
            //String sql = "select * from t_Book limit ?,?";
            DynamicParameter parameter = pageBean.getParameter();
            //添加两个分页查询参数
            //parameter.getParamValueList().add((pageBean.getPageNo()-1)*pageBean.getPageSize());
            //parameter.getParamValueList().add(pageBean.getPageSize());
            String sql = parameter.generateSqlForPage();


            //情况1：有查询参数
            if(parameter.getParamValueList().size()>0){
                //取得动态传参的参数值，转换为数组
                Object []args = parameter.getParamValueList().toArray();
                Object []args2 = {(pageBean.getPageNo()-1)*pageBean.getPageSize(),pageBean.getPageSize()};
                Object []args3 = Arrays.copyOf(args,args.length+args2.length);
                for(int i=0;i<args2.length;i++){
                    args3[args.length+i] = args2[i];
                }

                //*********修改的代码，用于支持动态查询参数*********//

                //3、执行查询
                //Object []args = {(pageBean.getPageNo()-1)*pageBean.getPageSize(),pageBean.getPageSize()};
                list = runner.query(sql,new BeanListHandler<Book>(Book.class),args3);

            }else{
                Object []args2 = {(pageBean.getPageNo()-1)*pageBean.getPageSize(),pageBean.getPageSize()};
                list = runner.query(sql,new BeanListHandler<Book>(Book.class),args2);
            }
            pageBean.setList(list);
            return pageBean;
        } catch (SQLException e) {
            throw new SystemBookDbException("分页查询所有用户错误："+e.getMessage());
        }
    }
}
